package consumer

import (
	"bp/conf"
	"bp/db"
	nsqMall "bp/internal/service/com/nsqMall"
	fo "bp/internal/nsqserver/failover"
	"bp/internal/nsqserver/shared"
	"bp/internal/service/com"
	"bp/internal/service/entity"
	"fmt"
	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

type OrderCancelConsumer struct {
	slog      *zap.SugaredLogger
	dao       *db.PgDao
	vars      *conf.VarsSection
	failover  *fo.NsqFailover
	entityHub *entity.EntityHub
	comHub    *com.ComHubForNsq
	topic     string
}

func New(
	nsqConfPtr *conf.NsqSection,
	slog *zap.SugaredLogger,
	pgdao *db.PgDao,
	vars *conf.VarsSection,
	failover *fo.NsqFailover,
	entityHub *entity.EntityHub,
	comHub *com.ComHubForNsq,
) (c *OrderCancelConsumer, err error) {
	topic := nsqMall.GetOrderCancelTopic()
	c = &OrderCancelConsumer{
		slog:      slog.With("module", fmt.Sprintf("%sConsumer", topic)),
		dao:       pgdao,
		vars:      vars,
		failover: failover,
		entityHub: entityHub,
		comHub:    comHub,
		topic:     topic,
	}
	config := nsq.NewConfig()
	consumer, err := nsq.NewConsumer(topic, shared.AppID, config)
	if err != nil {
		return
	}
	nsqLogger := shared.NewNoopNSQLogger(slog)
	consumer.SetLogger(
		nsqLogger,
		nsq.LogLevelError,
	)

	consumer.AddHandler(c)
	err = consumer.ConnectToNSQLookupd(nsqConfPtr.NsqLookupds[0])
	if err != nil {
		return
	}

	return
}
